<template>
  <div>
    <!-- 练习操作界面（子组件）需要三个参数：题目，当前索引值，剩余时间 -->
    <!-- <loading v-model="isLoading"></loading> -->
    <div v-if="showExerciseFrame">
      <the-exercise-frame :questions="questions" :myindex="index" :lastime="lastime" :workType="workType"/>
    </div> 
    <!-- 练习前确认界面 -->
    <div v-if="showPrepareExercise">
      <!-- 如果有未完成的练习则显示 -->
      <div v-if="isContinue">
        <msg 
          :title="confrimTitle" 
          :description="confrimMsg" 
          :icon="confrimIcon"
          >
          <template slot="buttons">
            <x-button type="primary" plain @click.native="getUnfinishQuestion">继续练习</x-button>
            <x-button type="primary" plain @click.native="getNewQuestionPrepare">全新练习</x-button>
            <x-button type="default" plain @click.native="gobackToHome">返回首页</x-button>  
          </template>
          </msg>
      </div>

      <!-- 无未完成的练习，则开始新的考试 -->
      <div v-if="isNew">
        <msg 
          :title="newConfrimTitle" 
          :description= newConfrimMsg
          :icon="newConfrimIcon"
        >
        <template slot="buttons">
          <x-button type="primary" plain @click.native="getNewQuestionPrepare">全新练习</x-button>
          <x-button type="default" plain @click.native="gobackToHome">返回首页</x-button>
        </template>
        </msg>
      </div>

    </div>
  </div>
</template>
<script>

import {
  Cell,
  XHeader,
  Group,
  Msg,
  Checklist,
  Toast,
  CheckIcon,
  Clocker,
  Card,
  Flexbox,
  FlexboxItem,
  XButton,
  dateFormat,
  XProgress,
  Loading,
  Badge,
  Confirm,
  Selector
} from 'vux'

import TheExerciseFrame from './commons/TheExerciseFrame'
import { mapGetters, mapActions } from 'vuex'
// const TheExerciseFrame = () => import('./commons/TheExerciseFrame')
export default {
  components: {
    Cell,
    XHeader,
    Group,
    Msg,
    Checklist,
    Toast,
    CheckIcon,
    Clocker,
    Card,
    Flexbox,
    FlexboxItem,
    XButton,
    dateFormat,
    XProgress,
    Loading,
    Badge,
    TheExerciseFrame,
    Confirm,
    Selector
  },
  data () {
    return {
      // 控制显示开关变量
      showExerciseFrame: false,
      showPrepareExercise: true,

      // 存在未完成练习的确认界面
      isContinue: false,
      confrimIcon: 'success',
      confrimTitle: '进入练习',
      confrimMsg: '存在未完成的练习,点击“继续练习”则继续上次练习。若放弃上次练习，重新抽题，请点击“全新练习”',
      // 全新练习确认界面
      isNew: false,
      newConfrimIcon: 'success',
      newConfrimTitle: '进入练习',
      newConfrimMsg: '本练习时间为120分钟，题目100道，其中选择题30题，判断题70题',
      ExerciseQuestionAmount: 100,
      ChoiceCount: 30,
      JudgmentCount: 70,
      examMin: 120,

      // 父子组件间传递数据
      questions: [], // 传递题目的变量
      index: 0, // 传递索引的变量
      lastime: 0, // 传递剩余时间的变量
      workType: 0, // 传递工种编号

      // 获得路由传递的workid
      workTypeId: 0,
      isLoading: false

    }
  },
  // beforeRouteEnter (to, from, next) {
  //   next(() => {
  //     this.ExerciseQuestionAmount = this.$store.state.sysconfig.ExerciseQuestionAmount
  //     this.ChoiceCount = this.$store.state.sysconfig.ChoiceCount
  //     this.JudgmentCount = this.$store.state.sysconfig.JudgmentCount
  //     this.examMin = this.$store.state.examSets.examMin
  //   })
  // },
  mounted () {
    // 获取路由来的工种代码
    if (this.$route.params.workid !== undefined) {
      this.workTypeId = this.$route.params.workid
    }
    // 进入页面显示新题还是继续练习
    console.log('时间键值：' + this.workTypeId + '-lastMins')
    console.log('题库键值：' + this.workTypeId)
    if (localStorage.hasOwnProperty(this.workTypeId + '-lastMins') && localStorage.hasOwnProperty(this.workTypeId)) {
      this.isContinue = true
      this.isNew = false
    } else {
      this.isContinue = false
      this.isNew = true
    }
  },
  computed: {
    ...mapGetters(['hasWork', 'allCardInfo', 'workTypeVK'])

    // 渲染总是提前，数据滞后，问题有待研究
    // newConfrimMsg: function () {
    //   // if (JSON.stringify(this.$store.state.sysconfig) !== '{}') {
    //   var msg = '本练习时间为'
    //   msg += this.examMin
    //   msg += '分钟，题目'
    //   msg += this.ExerciseQuestionAmount
    //   msg += '道，其中选择题'
    //   msg += this.ChoiceCount
    //   msg += '题，判断题'
    //   msg += this.JudgmentCount
    //   msg += '题'
    //   return msg
    //   // }
    // }
  },
  methods: {
    ...mapActions(['getExerciseInit', 'getSysconfig', 'getExamSet']),

    // 执行消费卡片
    getNewQuestionPrepare: function () {
      // this.$vux.loading.show({text: '提交请求'})
      var workType = this.workTypeId
      this.$http.get(this.$store.state.vxQuestionsGenTypeSubRdmExamPaper + '?workType=' + workType).then((res) => {
        var questions = res.data.subSectionQuestions
        if (questions.length > 0) {
          this.$http.post(this.$store.state.vxUsercardConsumeCard, {workType: workType}).then((res) => {
            if (res.data.code === 0) {
              this.$vux.loading.show({text: '消费成功'})
              setTimeout(() => {
                // this.$vux.loading.hide()
                // this.$vux.loading.show({text: '开始生成练习题'})
                // this.getNewQuestion(questions)
                console.log('传递的工种代码为：' + workType)
                this.getNewQuestion(questions, workType)
              }, 500)
            } else {
              var _this = this
              this.$vux.loading.hide()
              this.$vux.alert.show({
                title: '提示',
                content: '消费接口开小差啦，请稍后再来！',
                onHide () {
                  _this.$router.push({name: 'Home'})
                }
              })
            }
          })
        } else {
          var _this = this
          this.$vux.loading.hide()
          this.$vux.alert.show({
            title: '错误',
            content: '练习题生成失败，请稍后重试！',
            onHide () {
              _this.$router.push({name: 'Home'})
            }
          })
        }
      }).catch((error) => {
        var _this = this
        console.log(error)
        this.$vux.loading.hide()
        this.$vux.alert.show({
          title: '提示',
          content: '服务器开小差啦，请稍后再来！',
          onHide () {
            _this.$router.push({name: 'Home'})
          }
        })
      })
    },
    // 开始新的练习，通过服务器抽题获得题目
    getNewQuestion: function (questions, workType) {
      console.log('根据题型分组')
      var tmpquestionArray = questions
      console.log(tmpquestionArray)
      tmpquestionArray.sort(this.compareByPropertis('questionType'))
      console.log('对不同类型的题目进行随机排序')
      var Judgment = tmpquestionArray.slice(0, this.$store.state.sysconfig.JudgmentCount).sort(function () { return Math.random() > 0.5 ? -1 : 1 })
      var Choice = tmpquestionArray.slice(this.$store.state.sysconfig.JudgmentCount).sort(function () { return Math.random() > 0.6 ? -1 : 1 })
      var questionArray = Judgment.concat(Choice)
      console.log('重新组织数据')
      for (var i = 0; i < questionArray.length; i++) {
        var obj = JSON.parse(questionArray[i].content)
        var tmpArray = []
        Object.keys(obj).forEach(function (key) {
          tmpArray.push({key: key, value: obj[key]})
        })
        questionArray[i].content = tmpArray
        questionArray[i].checkedOption = []
      }
      console.log('将抽出的题目保存到本地')
      console.log(questionArray)
      // 临时存储的键名不能统一用question，因为存在多个工种，此处用工种ID为键名
      console.log('题目存储的键名为：' + workType)
      localStorage.setItem(workType, JSON.stringify(questionArray))

      this.index = 0
      this.lastime = this.$store.state.examSets.examMin * 60
      this.questions = questionArray
      this.workType = workType
      console.log('向做题界面子组件传递参数:' + this.index + ',' + this.lastime + ',' + this.workType)

        // 显示做题界面
      this.showExerciseFrame = true
        // 隐藏提示界面
      this.showPrepareExercise = false
        // 过渡效果结束
      this.$vux.loading.hide()
    },

    // 继续未完成的练习，通过本地存储获得或者通过服务器获得题目信息。
    getUnfinishQuestion: function () {
      var workType = this.workTypeId // 获取当前用户选择的工种代码
      console.log('继续未完成的题目,工种代码为:' + workType)
      // 开启过渡效果
      this.$vux.loading.show({text: '请稍候!'})
      // 准备题目、练习进度和时间
      var questionArray = JSON.parse(localStorage.getItem(workType))
      var i = 0
      while (questionArray[i].checkedOption.length === 1) {
        i++
        // console.log(i)
      }
      var lastMins = localStorage.getItem(workType + '-lastMins')
      // 向做题界面子组件传递参数
      this.index = i
      this.lastime = lastMins
      this.questions = questionArray
      this.workType = workType
      // 显示做题界面
      this.showExerciseFrame = true
      // 隐藏提示界面
      this.showPrepareExercise = false
      this.$vux.loading.hide()
    },

    gobackToHome: function () {
      this.$router.push({name: 'Home'})
    }
  },
  created () {
    // this.$nextTick(function () {
    //   this.getExerciseInit()
    // })
    this.getExerciseInit()
  }
}
</script>
<style scoped>

.selectCard{
  margin-bottom: 20px;
  margin-top: 20px;
}
</style>
